package com.his.server.account;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.his.server.consts.ServerConsts;
import com.his.server.dao.iface.UserInfoDAO;
import com.his.server.dao.impl.UserInfoDAOImpl;
import com.his.server.exception.DAOException;
import com.his.server.exception.DBException;
import com.his.server.jdbc.DBConnectionPool;
import com.his.server.logicdata.UserInfoLogicData;
import com.his.server.utils.dao.DAOFactory;
import com.his.server.utils.main.BaseContext;

import com.opensymphony.xwork2.ActionSupport;

public class UserLoginAction extends ActionSupport {
	
    private static final Log logger;
    UserInfoLogicData userInfoLogicData = 
    		(UserInfoLogicData) BaseContext.getAtribute(ServerConsts.SK_USERINFOLOGICDATA);
    DBConnectionPool dbConnectionPool = new DBConnectionPool();
    Connection Connection = null;
    PreparedStatement psmt = null;
    ResultSet rs = null;
    UserInfoDAO userInfoDAO = null;
    Class userInfoDAO_C = null;
    
    String name =  ServerConsts.EMPTY;
    String password =  ServerConsts.EMPTY;
    int usercount = 0;
    
	static 
    {
        logger = LogFactory.getLog(UserLoginAction.class);
    }
	
	@Override
    public String execute() throws Exception {
    	
		if (userInfoLogicData != null) {
			name = userInfoLogicData.getName();
			password = userInfoLogicData.getPassword();
		}
		
		try {
			Connection = dbConnectionPool.getConnction();
			userInfoDAO_C = (Class)DAOFactory.getDao(UserInfoDAO.class);
			userInfoDAO = (UserInfoDAO) userInfoDAO_C.newInstance();
			//userInfoDAO = (UserInfoDAO)DAOFactory.getDao(UserInfoDAO.class);
			userInfoDAO.setUserName(name);
			userInfoDAO.setPassword(password);
			userInfoDAO.doSqlExecute(Connection);
			usercount = userInfoDAO.getUserCount();
		} catch (DBException dbex) {
			
	    	if(logger.isTraceEnabled())
	    		logger.trace(dbex.getMessage());
			
			dbex.printStackTrace();
			
		} catch (DAOException daoex) {
			
			daoex.printStackTrace();
		}finally {
			
			if (userInfoDAO != null) {
				try {
					userInfoDAO.releasePstmt();
				} catch (DBException dbex) {
					
					dbex.printStackTrace();
				}
			}

			if (dbConnectionPool != null) {
				try {
					dbConnectionPool.releaseConnction(Connection);
				} catch (DBException dbex) {
					
					dbex.printStackTrace();
				}
			}						
		}
		
		if (usercount == 1){
			return super.execute();
		} else {
			return super.execute();
		}      
    }
}